﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Actions;
using blackhouse.BlackApart.Actions.Log;
using blackhouse.BlackApart.Business;
using System.IO;

namespace blackhouse.BlackApart.Web {
    public partial class Update : System.Web.UI.Page {

        IActionLog[] log;

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            this.ObjectDataSource1.ObjectCreated += new ObjectDataSourceObjectEventHandler(ObjectDataSource1_ObjectCreated);
            this.GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
            if (e.Row.RowType == DataControlRowType.DataRow) {
                GridViewRow gvr = e.Row as GridViewRow;
                if (gvr != null) {
                    gvr.Cells[3].Text = gvr.Cells[3].Text.ReplaceEx("\r\n", "<br />");
                }
            }
        }

        protected void ObjectDataSource1_ObjectCreated(object sender, ObjectDataSourceEventArgs e) {
            ( e.ObjectInstance as DalActionLog ).AssignSelect(this.log);
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            this.ClearUnusedReservationVariantFiles();

            ActionRunner runner = new ActionRunner(Factory.Instance().GetDataFactory().GetActionData(), new DaActionLog(Factory.Instance().GetDataFactory().GetActionData()));
            runner.MakeAutomaticStatusChange();
            runner.DeleteInterruptedReservations();
            while (runner.GotoNextAction())
                runner.RunAction();
            this.log = runner.GetAllLogs();
        }

        protected void ClearUnusedReservationVariantFiles() {
            SearchReservationPerRequest.RemoveUnnecessaryFiles(new DirectoryInfo(Server.MapPath("/SavedReservations")), TimeSpan.FromDays(1));
        }

    }
}